/**
 * @see https://umijs.org/docs/max/access#access
 * 权限定义文件
 * 根据用户信息和权限列表，定义各种权限判断函数
 */

interface InitialState {
  currentUser?: {
    id?: string;
    name?: string;
    avatar?: string;
    email?: string;
    role?: string;
    permissions?: string[];
  };
  permissions?: string[];
}

export default function access(initialState: InitialState | undefined) {
  const { currentUser } = initialState ?? {};
  const permissions = currentUser?.permissions || [];
  const role = currentUser?.role;

  // 辅助函数：检查是否有某个权限
  const hasPermission = (permission: string) => permissions.includes(permission);

  // 辅助函数：检查是否有任意一个权限
  const hasAnyPermission = (perms: string[]) => perms.some(p => permissions.includes(p));

  // 辅助函数：检查是否有所有权限
  const hasAllPermissions = (perms: string[]) => perms.every(p => permissions.includes(p));

  return {
    // ========== 角色权限 ==========
    isAdmin: role === 'admin',
    isUser: role === 'user',
    isGuest: role === 'guest',

    // ========== Dashboard 权限 ==========
    canViewDashboard: hasPermission('dashboard:view'),
    canViewDashboardAnalysis: hasPermission('dashboard:analysis:view'),
    canViewDashboardMonitor: hasPermission('dashboard:monitor:view'),
    canViewDashboardWorkplace: hasPermission('dashboard:workplace:view'),

    // ========== Form 权限 ==========
    canViewForm: hasPermission('form:view'),
    canViewFormBasic: hasPermission('form:basic:view'),
    canViewFormStep: hasPermission('form:step:view'),
    canViewFormAdvanced: hasPermission('form:advanced:view'),

    // ========== List 权限 ==========
    canViewList: hasPermission('list:view'),
    canViewListTable: hasPermission('list:table:view'),
    canViewListBasic: hasPermission('list:basic:view'),
    canViewListCard: hasPermission('list:card:view'),

    // ========== Profile 权限 ==========
    canViewProfile: hasPermission('profile:view'),
    canViewProfileBasic: hasPermission('profile:basic:view'),
    canViewProfileAdvanced: hasPermission('profile:advanced:view'),

    // ========== Account 权限 ==========
    canViewAccount: hasPermission('account:view'),
    canViewAccountCenter: hasPermission('account:center:view'),
    canViewAccountSettings: hasPermission('account:settings:view'),

    // ========== Result 权限 ==========
    canViewResult: hasPermission('result:view'),
    canViewResultSuccess: hasPermission('result:success:view'),
    canViewResultFail: hasPermission('result:fail:view'),

    // ========== Exception 权限 ==========
    canViewException: hasPermission('exception:view'),

    // ========== 通用权限检查函数 ==========
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,

    // 兼容旧代码
    canAdmin: role === 'admin',
  };
}
